# _*_coding:utf-8 _*_

import requests
import time
import hashlib
import json
import traceback
import ast
import redis
from datetime import datetime, timedelta

'''md5加密函数'''


def md5cd(data1):
    m = hashlib.md5(data1.encode(encoding='utf-8'))  # 参数必须是byte类型，否则报Unicode-objects must be encoded before hashing错误
    return m.hexdigest().lower()


def md5value(key):
    input_name = hashlib.md5()
    input_name.update(key.encode("utf-8"))
    print("大写的32位" + (input_name.hexdigest()).upper())
    print("大写的16位" + (input_name.hexdigest())[8:-8].upper())
    print("小写的32位" + (input_name.hexdigest()).lower())


'''配置数据'''

conf = {
    'sndd': {'appid': 'client_user_agency', 'secret': '39e7ec22b2d0cebe',
             'url1': 'http://contest-server-agency.igetcool.com',
             'url2': 'http://contest-server-qa.svc.igetcool.com/', 'token': '', 'time': '', 'sid': ''},
}

'''少年得到动态黑名单，拦截注册用户'''


def dtsndd(hm):
    try:
        tnow = int(time.time() * 1000)
        # print(tnow)
        appid = conf['sndd'].get('appid')
        secret = conf['sndd'].get('secret')
        sig1 = secret + '&' + str(tnow)
        sig = md5cd(sig1)
        url1 = conf['sndd'].get('url1')
        token = ''

        '''获取token'''
        # aheaders = {'Content-Type': 'application/json'}
        # rt = requests.post(urltoken, data=json.dumps(datat), headers=aheaders)
        bdurl = url1 + '/option/api/userAgency/getOauthAccessToken?' \
                       'appId=' + appid + '&timestamp=' + str(tnow) + '&sign=' + sig
        rt = requests.get(bdurl)
        # print(rt.status_code)
        if rt.status_code == 200:
            # print(rt.text)
            token1 = ast.literal_eval(rt.text)
            token = token1['data']  # 解析到token
        else:
            return 'cw'

        '''注册信息查询接口'''
        urlcon = url1 + '/option/api/userAgency/getUserId/'
        datacon = 'appId=' + appid + '&accessToken=' + token + '&phone=' + hm
        hacom = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'accept': '*/*',
            'Request-Origion': 'SwaggerBootstrapUi'
        }
        rcon = requests.post(urlcon, data=datacon, headers=hacom)
        if rcon.status_code == 200:
            print(rcon.status_code)
            print('号码查询', rcon.text)
            d2 = rcon.text
            if 'null' in d2:
                print('此号码不是注册用户，通过处理')
                return 'tg'
            else:
                print('此号码是注册用户，拦截处理')
                return 'lj'
        else:
            return 'cw'
    except Exception as er:
        print("少年得到函数错误:")
        print(er)
        print(traceback.format_exc())
        return 'cw'


'''少年得到动态黑名单,拦截非注册用户'''


def dtsnddzc(hm):
    try:
        tnow = int(time.time() * 1000)
        # print(tnow)
        appid = conf['sndd'].get('appid')
        secret = conf['sndd'].get('secret')
        sig1 = secret + '&' + str(tnow)
        sig = md5cd(sig1)
        url1 = conf['sndd'].get('url1')
        token = ''

        '''获取token'''
        # aheaders = {'Content-Type': 'application/json'}
        # rt = requests.post(urltoken, data=json.dumps(datat), headers=aheaders)
        bdurl = url1 + '/option/api/userAgency/getOauthAccessToken?' \
                       'appId=' + appid + '&timestamp=' + str(tnow) + '&sign=' + sig
        rt = requests.get(bdurl)
        # print(rt.status_code)
        if rt.status_code == 200:
            # print(rt.text)
            token1 = ast.literal_eval(rt.text)
            token = token1['data']  # 解析到token
        else:
            return 'cw'

        '''注册信息查询接口'''
        urlcon = url1 + '/option/api/userAgency/getUserId/'
        datacon = 'appId=' + appid + '&accessToken=' + token + '&phone=' + hm
        hacom = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'accept': '*/*',
            'Request-Origion': 'SwaggerBootstrapUi'
        }
        rcon = requests.post(urlcon, data=datacon, headers=hacom)
        if rcon.status_code == 200:
            print(rcon.status_code)
            print('号码查询', rcon.text)
            d2 = rcon.text
            if 'null' not in d2:
                print('此号码不是注册用户，通过处理')
                return 'tg'
            else:
                print('此号码是注册用户，拦截处理')
                return 'lj'
        else:
            return 'cw'
    except Exception as er:
        print("少年得到函数错误:")
        print(er)
        print(traceback.format_exc())
        return 'cw'


'''少年得到uid被叫动态改写'''


def uidsn(hm):
    try:
        hmq = [hm[3:]]
        tnow = int(time.time() * 1000)
        # print(tnow)
        appid = conf['sndd'].get('appid')
        secret = conf['sndd'].get('secret')
        sig1 = secret + '&' + str(tnow)
        sig = md5cd(sig1)
        url1 = conf['sndd'].get('url1')
        # url2 = conf['sndd'].get('url1')
        token = ''
        '''获取token'''
        # aheaders = {'Content-Type': 'application/json'}
        # rt = requests.post(urltoken, data=json.dumps(datat), headers=aheaders)
        bdurl = url1 + '/option/api/userAgency/getOauthAccessToken?' \
                       'appId=' + appid + '&timestamp=' + str(tnow) + '&sign=' + sig
        rt = requests.get(bdurl)
        # print(rt.status_code)
        if rt.status_code == 200:
            # print(rt.text)
            token1 = ast.literal_eval(rt.text)
            token = token1['data']  # 解析到token
            # print(token)
        else:
            return ''

        '''uid查询用户手机号码接口'''
        urlcon = url1 + '/option/api/userAgency/getBatchUserPhone'
        # datacon = 'appId=' + appid + '&accessToken=' + token + '&userIdList=' + str(hmq)
        datacon = {"accessToken": token, "appId": appid, "userIdList": hmq}
        hacom = {'Content-Type': 'application/json'}
        rcon = requests.post(urlcon, data=json.dumps(datacon), headers=hacom)
        if rcon.status_code == 200:
            # print(rcon.status_code)
            # print('号码查询', rcon.text)
            # d2 = rcon.text
            uidtohm = ast.literal_eval(rcon.text)
            # print(uidtohm)
            uidtohm1 = uidtohm['data'].get(hm[3:], '')  # 解析到号码
            # print(uidtohm1)
            if uidtohm1:
                print('此号码是注册用户，返回uid转换后的号码')
                return hm[:3] + uidtohm1
            else:
                print('此号码不是注册用户，查不到号码，返回空')
                return ''
        else:
            print('查询uid错误')
            return ''
    except Exception as er:
        print("少年得到uidtohm函数错误:")
        print(er)
        print(traceback.format_exc())
        return ''


'''动态黑名单函数'''


def hmd(hmdid, hm):
    try:
        # hmdid = hmdid.split('/')
        if hmdid == 'sndd':
            jg = dtsndd(hm)
            return jg
        elif hmdid == 'snddzc':
            jg = dtsnddzc(hm)
            return jg
        else:
            print('无此动态黑名单库')
            return 0
    except Exception as er:
        print("动态黑名单函数错误:")
        print(er)
        print(traceback.format_exc())
        return 0


'''动态改写被叫'''


def uidgx(gxid, hm):
    try:
        # hmdid = hmdid.split('/')
        if gxid == 'sngx':
            jg = uidsn(hm)
            return jg
        else:
            print('无此改写uid')
            return 0
    except Exception as er:
        print("动态uid改写函数错误:")
        print(er)
        print(traceback.format_exc())
        return 0


'''uid复印出号码'''


def uidfz(hm, num, name, gxid='sngx'):
    try:
        # hmdid = hmdid.split('/')
        if gxid == 'sngx' and numpd(name, num):
            jg = uidsn('aaa' + str(hm))
            return jg[3:]
        else:
            print('无此改写uid')
            return 0
    except Exception as er:
        print("动态uid改写函数错误:")
        print(er)
        print(traceback.format_exc())
        return 0


'''使用次数增加'''


def numadd(name):
    try:
        # 核算当天还剩余多少秒
        current_time1 = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # print(current_time1)  # 打印当天时间
        current_time2 = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
        # print(current_time2)  # 打印当天凌晨时间，其实就是加一天，是分秒全部0
        d1 = datetime.strptime(current_time1, '%Y-%m-%d %H:%M:%S')
        d2 = datetime.strptime(current_time2, '%Y-%m-%d %H:%M:%S')
        # print(((d2 - d1).total_seconds()))  # 打印剩余时间
        gqtime = int((d2 - d1).total_seconds())
        d = 0
        # 连接
        r = redis.Redis(host="127.0.0.1", port=6379, password="Dws666888", db=4, decode_responses=True)
        dr = r.get('snuid:' + str(name))
        if dr:
            d = dr
        # 增加次数
        r.set('snuid:' + str(name), int(d)+1)
        # 设置过期时间
        e = r.expire('snuid:' + str(name), gqtime)
        r.close()
    except Exception as er:
        print("加使用次数函数错误:")
        print(er)
        print(traceback.format_exc())
        return 0


'''判断使用次数'''


def numpd(name, num):
    try:
        d = 0
        # 连接
        r = redis.Redis(host="127.0.0.1", port=6379, password="Dws666888", db=4, decode_responses=True)
        dr = r.get('snuid:' + str(name))
        r.close()
        if dr:
            d = dr
        if int(d) <= int(num):
            # print('现在返回lj')
            return 'tg'
        else:
            # print('现在返回通过')
            return 0
    except Exception as er:
        print("次数判断错误:")
        print(er)
        print(traceback.format_exc())
        return 0
